<?php

namespace backend\controllers;

use backend\models\Arrange;
use backend\models\Search;
use common\models\SurgicalItems;
use common\models\UserModel;
use Yii;
use common\models\BillingOperation;
use backend\models\BillingOperation as BillingOperationSearch;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\SuppliesBound;
use common\models\Supplies;
use common\models\SupplieOrder;
use common\models\SupplieOrderDetail;

/**
 * BillingController implements the CRUD actions for BillingOperation model.
 */
class BillingController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BillingOperation models.
     * @return mixed
     */
    public function actionIndex()
    {
        
        $searchModel = new BillingOperationSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,

        ]);
    }

    /**
     * Displays a single BillingOperation model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = BillingOperation::find()->with(['client','surgical','hakim','assistant','nurse','counselor'])->where(['id'=>$id])->one();

        if($model==null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        return $this->render('view', [
            'model' => $model,
        ]);
    }



    public function actionSuccess()
    {
        return $this->render('success');
    }

    /**
     * Creates a new BillingOperation model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BillingOperation();
        $query = new Search();
        $select = $query->search(Yii::$app->request->queryParams);
        $data = $select->one();
        $list = $model->getOption();
        $hakim = UserModel::find()->where(['and',['=','store_id',Yii::$app->user->identity->store_id],['=','position_id',6]])->all();
        $assistant = UserModel::find()->where(['and',['=','store_id',Yii::$app->user->identity->store_id],['=','position_id',7]])->all();
        $nurse = UserModel::find()->where(['and',['=','store_id',Yii::$app->user->identity->store_id],['=','position_id',8]])->all();
        $role = [
            'hakim'=>$hakim,
            'assistant'=>$assistant,
            'nurse' => $nurse
        ];
        if(Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $post['BillingOperation']['counselor_id'] = Yii::$app->user->identity->id;
            $post['BillingOperation']['store_id'] = Yii::$app->user->identity->store_id;
            $post['BillingOperation']['status'] = 100;
            $post['BillingOperation']['client_id'] = $data['id'];
            $post['BillingOperation']['sale_id'] = $data['sale_id'];
            // 查出手术项目对应所需要的耗材有哪些
            $bound = SuppliesBound::find()->select('supplie_id,number')->asArray()->where(['operation_id'=>$post['BillingOperation']['surgical_id']])->all();

            $transaction = Yii::$app->db->beginTransaction();
            try{
                if ($model->load($post)) {
                    $model->save();
                    //获取新增的手术单的ID
                    $billingId = $model->getPrimaryKey();

                    //新增该手术单所需要的耗材的订单
                    $supplieOrder = new SupplieOrder();
                    $supplieOrder->bill_id = $billingId;
                    $supplieOrder->client_id = $data['id'];
                    $supplieOrder->order_number = 'MLY'.Yii::$app->user->identity->id.rand(1000,9999).time();
                    $supplieOrder->store_id = Yii::$app->user->identity->store_id;
                    $supplieOrder->hakim_id = Yii::$app->user->identity->id;
                    $supplieOrder->status = $data['id'];
                    $supplieOrder->created_time = time();
                    
                    if($supplieOrder->save()){
                        //获取到刚刚添加的耗材订单的id
                        $supplieOrderId = $supplieOrder->getPrimaryKey();
                        
                        //判断该手术项目下有没有绑定耗材
                        if($bound){
                            //循环获取手术项目所对应的耗材,并且更改耗材库存，组合数据 *该数据是在手术项目管理中详情页面添加的，
                            $supplieOrderDetail = [];
                            foreach ($bound as $key => $value) {
                                $supplieOrderDetail[] = [
                                    'supplie_id' => $value['supplie_id'],
                                    'number' => $value['number'],
                                    'order_id' => $supplieOrderId,
                                    'created_time' => time()
                                ];
                                Supplies::updateAllCounters(['stock'=>-$value['number']],['id'=>$value['supplie_id']]);
                            }

                            //批量插入到订单详情表
                            $createDetail = Yii::$app->db->createCommand()->batchInsert(SupplieOrderDetail::tableName(),
                        
                                ['supplie_id', 'number', 'order_id', 'created_time'],
                        
                                $supplieOrderDetail
                    
                            )->execute();
                            //如果插入失败，抛出异常
                            if($createDetail == 0){

                                throw new BadRequestHttpException("订单详情插入失败");
                                
                            } 
                        }
                    }

                        
                    
                }else{
                    throw new BadRequestHttpException('数据添加失败！');
                }


                $transaction->commit();
                return $this->redirect(['view', 'id' => $model->id]);
            
            }catch(\Exception $e){
                $transaction->rollBack();
                throw new BadRequestHttpException("数据添加失败！");
                
            }
            
        }else {
            return $this->render('create', [
                'model'=> $model,
                'data' => $data,
                'query'=> $query,
                'list' => $list,
                'role' => $role

            ]);
        }
    }

    public function actionAjaxPrice()
    {
        if(Yii::$app->request->isAjax){
            $post = Yii::$app->request->post('id');
            $price = SurgicalItems::findOne($post)['guide_price'];
            return $price;
        }
        return false;
    }
    public function actionArrangeOperation()
    {
        $searchModel = new Arrange();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('arrange-operation', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /***
     * 现场咨询师搜索用户信息功能
     * @return string
     */
    public function actionSearch(){
        $model = new BillingOperation();
        $query = new Search();
        $select = $query->search(Yii::$app->request->queryParams);
        $data = $select->one();
        return $this->render(
            'search',
            [
                'model'=>$model,
                'data'=>$data,
                'query'=>$query
            ]);
    }

    /**
     * Updates an existing BillingOperation model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $this->findModel($id)->updateAll(['status'=>168],['id'=>$id]);
        SupplieOrder::updateAll(['status'=>20],['bill_id'=>$id]);
        return $this->redirect(['view', 'id' => $id]);
    }

    /**
     * Deletes an existing BillingOperation model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
    * @param $id
    * @return \yii\web\Response
    */

    public function actionDelall()
    {
        if(!Yii::$app->request->isAjax && !Yii::$app->request->isPost){
            return '未知错误';
        }
        $id = implode(',',$_POST['id']);
        $model = new BillingOperation();
        $model->deleteAll("id in($id)");
        return $this->redirect(['index']);
    }

    public function actionRecord($id)
    {
        $model = BillingOperation::find()->with(['client','surgical','hakim','assistant','nurse','counselor'])->where(['and',['client_id'=>$id],['store_id'=>Yii::$app->user->identity->store_id]])->all();
        if(!$model){
            return '暂无手术记录！';
        }
        return $this->renderAjax('record',['model'=>$model]);
    }

    /**
    * 批量修改功能，这只是一个模型，你可以向里面添加你想要的内容
    * @param $id
    * @return \yii\web\Response
    */
    public function actionUpdateall()
    {
        if(!Yii::$app->request->isAjax && !Yii::$app->request->isPost){
            return '未知错误';
        }
        $id = implode(',',$_POST['id']);
        $model =new BillingOperation();
        $model->updateAll(['link_status'=>1],"id in($id)");
        return $this->redirect(['index']);
    }
    /**
     * Finds the BillingOperation model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BillingOperation the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BillingOperation::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
